package com.crazymaker.demo.auth;

import com.crazymaker.springcloud.standard.utils.AuthUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.StringUtils;
import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JwtDemo
{

    @Test
    public void testBaseJWT()
    {
        try
        {
            String subject = "session id";
            String salt = "user password";
            String token = AuthUtils.buildToken(subject, salt);
            log.info("token=" + token);
            //输出demo为：token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJzZXNzaW9uIGlkIiwiZXhwIjoxNTc5MzE1NzE3LCJpYXQiOjE1Nzg0NTE3MTd9.iANh9Fa0B_6H5TQ11bLCWcEpmWxuCwa2Rt6rnzBWteI

            //以·点分割. 这里需要转义
            String[] parts = token.split("\\." );

            String headerJson;
            String payloadJson;
            headerJson = StringUtils.newStringUtf8(Base64.decodeBase64(parts[0]));
            log.info("parts[0]=" + headerJson);
            //输出demo为：parts[0]={"typ":"JWT","alg":"HS256"}


            payloadJson = StringUtils.newStringUtf8(Base64.decodeBase64(parts[1]));
            log.info("parts[1]=" + payloadJson);
            //输出demo为：parts[1]={"sub":"session id","exp":1579315535,"iat":1578451535}


        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    @Test
    public void testJWTWithClaim()
    {
        try
        {

            Map<String,String> claims = new HashMap<String,String>();//创建payload的私有声明（根据特定的业务需要添加，如果要拿这个做验证，一般是需要和jwt的接收方提前沟通好验证方式的）
            claims.put("uid", "123...");
            claims.put("user_name", "admin");
            claims.put("nick_name","管理员");

            String subject = "session id";
            String salt = "user password";
            String token = AuthUtils.buildToken(subject, salt,claims);
            log.info("token=" + token);
            //输出demo为：token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJzZXNzaW9uIGlkIiwiZXhwIjoxNTc5MzE1NzE3LCJpYXQiOjE1Nzg0NTE3MTd9.iANh9Fa0B_6H5TQ11bLCWcEpmWxuCwa2Rt6rnzBWteI

            //以·点分割. 这里需要转义
            String[] parts = token.split("\\." );

            String headerJson;
            String payloadJson;
            headerJson = StringUtils.newStringUtf8(Base64.decodeBase64(parts[0]));
            log.info("parts[0]=" + headerJson);
            //输出demo为：parts[0]={"typ":"JWT","alg":"HS256"}


            payloadJson = StringUtils.newStringUtf8(Base64.decodeBase64(parts[1]));
            log.info("parts[1]=" + payloadJson);
            //输出demo为：parts[1]={"uid":"123...","sub":"session id","user_name":"admin","nick_name":"管理员","exp":1579317358,"iat":1578453358}

        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}
